var firebaseExample = {}

var myDataRef = new Firebase('https://incandescent-heat-443.firebaseio.com/');

firebaseExample.Init = function() {
    $('#messageInput').keypress(function(e){
        if(e.keyCode == 13) {
            var _name = $('#nameInput').val();
            var _text = $('#messageInput').val();
            // myDataRef.set({name: _name, text: _text});
            myDataRef.push({name: _name, text: _text, uid: 'thanhlt', date: Date()});
            $('#messageInput').val('');
        }
    });
    // child_added
    myDataRef.on('child_added', function(snapshot){
        console.log('comming ...');
        var message = snapshot.val();
        console.log(message);
        displayChatMessage(message.name, message.text);
    }, function (errorObject) {
        console.log('Failed: '+ errorObject.code);
    });

    // child_changed
    myDataRef.on('child_changed', function(snapshot) {
        var changedPost = snapshot.val();        
        displayChatMessage(changedPost.name, changedPost.text);
        console.log('Updating ...');
    });

    // child_removed
    myDataRef.on('child_removed', function(snapshot) {
        var deletePost = snapshot.val();
        console.log('The post has been deleted ' + deletePost.name);        
    });

    function displayChatMessage(name, text) {
        $('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messageDiv'));
        $('#messageDiv')[0].scrollTop = $('#messageDiv')[0].scrollHeight;
    }
};

jQuery(document).ready(function($) {
    firebaseExample.Init();
});